package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Result queryById(Long id) {
        // 缓存穿透
        // Shop shop = queryWithPassThrough(id);
//        Shop shop = queryWithMutex(id);
//        if (shop == null) {
//            return Result.fail("店铺不存在");
//        } else {
//            return Result.ok(shop);
//        }
        Shop shop = redisUtil.getWithLogicalExpireTime(
                RedisConstants.CACHE_SHOP_KEY + id,
                Shop.class,
                () -> getById(id),
                RedisConstants.CACHE_SHOP_TTL, TimeUnit.SECONDS);
        if (shop == null) {
            return Result.fail("店铺不存在");
        } else {
            return Result.ok(shop);
        }
    }

    // 互斥锁解决缓存击穿
    private Shop queryWithMutex(Long id) {
        // 1. 从缓存查询
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        String jsonStr = stringRedisTemplate.opsForValue().get(key);
        if (jsonStr != null) {
            if (jsonStr.isEmpty()) {
                return null;
            } else {
                return JSONUtil.toBean(jsonStr, Shop.class);
            }
        }
        // 2. 缓存中不存在，重建缓存
        Shop shop;
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        try {
            if (!isLock) {
                Thread.sleep(50);
                // 重新在缓存中查询数据
                return queryWithMutex(id);
            } else {
                // 缓存重建
                shop = getById(id);
                if (shop == null) {
                    stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                } else {
                    stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            unlock(lockKey);
        }
        return shop;
    }

    @Override
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺ID不能为空");
        }
        // 1. 先更新数据库
        this.updateById(shop);
        // 2. 删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }

    private boolean tryLock(String key) {
        // 有效期一般是比业务的执行时间长一点即可
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 3, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }

    // 解决缓存穿透
    public Shop queryWithPassThrough(Long id) {
        // 1. 从redis查询商品信息
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        String jsonStr = stringRedisTemplate.opsForValue().get(key);
        // 2. 判断是否存在
        if ("".equals(jsonStr)) {
            return null;
        }
        if (StrUtil.isNotBlank(jsonStr)) {
            // 3. 存在直接返回
            return null;
        }
        // 4. 不存在查询数据库
        Shop shop = getById(id);
        if (shop == null) {
            // 5. 缓存空值，解决缓存穿透
            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        // 6. 数据库存在写入缓存，并设置过期时间，做个兜底方案
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }

    // 逻辑过期解决缓存穿透
    public Shop queryWithLogicalExpire(Long id) {
        // 1. 从缓存查询
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        // 2. 查询是否存在
        String jsonStr = stringRedisTemplate.opsForValue().get(key);
        // 3. 命中，需要判断过期时间
        LocalDateTime now = LocalDateTime.now();
        RedisData redisData = JSONUtil.toBean(jsonStr, RedisData.class);
        // 4. 如果过期，获取互斥锁开启新线程执行缓存重建
        if (redisData.getExpireTime().isBefore(now)) {
            // 5. 执行缓存重建
            String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
            boolean isLock = tryLock(lockKey);
            if (isLock) {
                // 开启新线程
                CACHE_REBUILD_EXECUTOR.submit(() -> {
                    try {
                        // 缓存重建
                        rebuildCache(id, now);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    } finally {
                        unlock(lockKey);
                    }
                });
            }
        }
        // 6. 不管有没有过期，都返回旧的数据
        return JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
    }

    public void rebuildCache(Long id, LocalDateTime now) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        Shop shop = getById(id);
        if (shop == null) {
            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
        } else {
            RedisData redisData = new RedisData();
            redisData.setExpireTime(now.plusSeconds(RedisConstants.CACHE_SHOP_TTL));
            redisData.setData(shop);
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
        }
    }

    // 用于缓存预热
    public void saveShop2Redis(Long id, Long expireSeconds) {
        // 1. 查询店铺数据
        Shop shop = getById(id);
        if (shop == null) {
            throw new RuntimeException("店铺不存在");
        }
        // 2. 封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        // 3. 写入redis，没有添加ttl的实际过期时间
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }
}
